<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="炼厂" prop="refineryId">
        <el-select  v-model="queryParams.refineryId" placeholder="请选择炼厂">
          <el-option
            v-for="item in filteredRefinerys"
            :key="item.id"
            :label="item.refineryName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"

        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"

        >修改</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"

        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"

        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="onwayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购计划" align="center" prop="planId" :formatter="planIdFormat" width="160" />
      <el-table-column label="炼厂" align="center" prop="refineryId" :formatter="refineryIdFormat"    />
<!--      <el-table-column label="已发量" align="center" prop="send" />-->
      <el-table-column label="已发车数量 (车)" align="center" prop="sendCarCount" width="120" />
      <el-table-column label="已发量 (吨)" align="center" prop="sendWeight" width="100" />
      <el-table-column label="出发时间" align="center" prop="startTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计到达时间" align="center" prop="arriveTime" width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arriveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="到库车数量" align="center" prop="arriveCarCount"  />-->
<!--      <el-table-column label="到库重量" align="center" prop="arriveWeight"  />-->
      <el-table-column label="异常情况" align="center" prop="error"  />
      <!-- <el-table-column label="备注" align="center" prop="remark"  /> -->
      <el-table-column label="上报用户" align="center" prop="reportUserId" :formatter="reportPersonFormat" />
      <el-table-column label="状态" align="center" prop="extra1"  :formatter="extra1Format" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-home"
            v-if="scope.row.extra1<2"
            @click="handleStatus2(scope.row)"

          >到站</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            v-if="scope.row.extra1<3"
            @click="handleStatus3(scope.row)"

          >收油</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"

          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改在途油信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" label-position="top" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="炼厂" prop="refineryId">
              <el-select v-model="form.refineryId" placeholder="请选择炼厂" style="width: 90%;">
                <el-option
                  v-for="item in filteredRefinerys"
                  :key="item.id"
                  :label="item.refineryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已发车数量 (车)" prop="sendCarCount">
              <el-input-number
                :min="1"
                :step="1"
                :precision="0"
                v-model="form.sendCarCount"
                placeholder="请输入已发车数量"
                style="width: 90%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已发量 (吨)" prop="sendWeight">
              <el-input-number
                :min="0"
                :precision='4'
                v-model="form.sendWeight"
                placeholder="请输入已发量"
                style="width: 90%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出发时间" prop="startTime">
              <el-date-picker clearable size="small"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择出发时间"
                style="width: 90%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计到达时间" prop="arriveTime">
              <el-date-picker clearable size="small"
                v-model="form.arriveTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择预计到达时间"
                style="width: 95%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态"  prop="extra1">
              <el-select v-model="form.extra1" filterable placeholder="选择状态" style="width: 90%;" >
                <el-option
                  v-for="user in filteredStatus"
                  :key="user.value"
                  :label="user.label"
                  :value="user.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报用户"  prop="reportUserId">
              <el-input v-model="userName" readonly style="width: 95%;" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常情况" prop="error">
              <el-input v-model="form.error" type="textarea" placeholder="请输入异常情况" style="width: 98%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOnway, getOnway, delOnway, addOnway, updateOnway, exportOnway } from "@/api/onway/onway";
import { listUserNoPage } from '@/api/system/user'
import { listRefineryNoPage } from '@/api/report/refinery'
import { getPlan, listPlanNoPage } from '@/api/plan/plan'

export default {
  name: "Onway",
  data() {
    return {
      plan:{},
      filteredRefinerys:[],
      filteredUsers:[],
      filteredPlans:[],
      filteredStatus:[{value:1,label:'在途'},{value:2,label:'到站'},{value:3,label:'收油'},],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 在途油信息表格数据
      onwayList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // id字典
      idOptions: [],
      // 创建人字典
      createByOptions: [],
      // 创建时间字典
      createTimeOptions: [],
      // 修改人字典
      updateByOptions: [],
      // 修改时间字典
      updateTimeOptions: [],
      // 修改时间字典
      extra1Options: [],
      // 修改时间字典
      extra2Options: [],
      // 修改时间字典
      extra3Options: [],
      // 修改时间字典
      extra4Options: [],
      // 采购计划字典
      planIdOptions: [],
      // 炼厂字典
      refineryIdOptions: [],
      // 已发量字典
      sendOptions: [],
      // 已发车数量字典
      sendCarCountOptions: [],
      // 已发量字典
      sendWeightOptions: [],
      // 出发时间字典
      startTimeOptions: [],
      // 预计到达时间字典
      arriveTimeOptions: [],
      // 到库车数量字典
      arriveCarCountOptions: [],
      // 到库重量字典
      arriveWeightOptions: [],
      // 异常情况字典
      errorOptions: [],
      // 备注字典
      remarkOptions: [],
      // 上报用户字典
      reportUserIdOptions: [],


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        refineryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planId: [
          { required: true, message: '采购计划不能为空', trigger: 'blur' }
        ],
        refineryId: [
          { required: true, message: '炼厂不能为空', trigger: 'blur' }
        ],
        sendCarCount: [
          { required: true, message: '已发车数量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        sendWeight: [
          { required: true, message: '已发量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '出发时间不能为空', trigger: 'blur' }
        ],
        arriveTime: [
          { required: true, message: '预计到达时间不能为空', trigger: 'blur' },
          { validator: this.validateArriveTime, trigger: 'blur' } // 添加自定义校验
        ],
        // arriveCarCount: [
        //   { required: true, message: '到库车数量不能为空', trigger: 'blur' },
        //   { type: 'number', message: '必须为数字', trigger: 'blur' }
        // ],
        arriveWeight: [
          // { required: true, message: '到库重量不能为空', trigger: 'blur' },
          { type: 'number', message: '必须为数字', trigger: 'blur' }
        ],
        extra1:[ { required: true, message: '状态不能为空', trigger: 'blur' }],
        reportUserId: [
          { required: true, message: '上报用户不能为空', trigger: 'blur' }
        ],
      },
      userName: this.$store.getters.name,
      userId: this.$store.getters.userId,
    };
  },
  created() {
    this.fetchRefinerys()
    this.fetchUsers()
    this.fetchPlans()
    let planId = this.$route.params && this.$route.params.planId;
    this.fetchPaln(planId)

    this.form.planId=planId
    this.queryParams.planId=planId
    this.getList();
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra1Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra2Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra3Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra4Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.planIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.refineryIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sendOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sendCarCountOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sendWeightOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.startTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.arriveTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.arriveCarCountOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.arriveWeightOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.errorOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.remarkOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.reportUserIdOptions = response.data;
    });
  },
  methods: {
    validateArriveTime(rule, value, callback) {
      const startTime = new Date(this.form.startTime);
      const arriveTime = new Date(value);
      if (arriveTime < startTime) {
        callback(new Error('预计到达时间不得早于出发时间'));
      } else {
        callback();
      }
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    fetchPaln(id){
      getPlan(id).then(response => {
        this.plan = response.data;
      });
    },
    fetchPlans() {
      this.loading=true;
      listPlanNoPage().then(response => {
          this.filteredPlans = response.rows;
          this.loading = false;
        }
      );
    },
    fetchRefinerys() {
      this.loading=true;
      listRefineryNoPage().then(response => {
          this.filteredRefinerys = response.rows;
          this.loading = false;
        }
      );
    },
    /** 查询在途油信息列表 */
    getList() {
      this.loading = true;
      // this.queryParams.planId=this.form.id
      listOnway(this.queryParams).then(response => {
        this.onwayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // id字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 创建人字典翻译
    createByFormat(row, column) {
      return this.selectDictLabel(this.createByOptions, row.createBy);
    },
    // 创建时间字典翻译
    createTimeFormat(row, column) {
      return this.selectDictLabel(this.createTimeOptions, row.createTime);
    },
    // 修改人字典翻译
    updateByFormat(row, column) {
      return this.selectDictLabel(this.updateByOptions, row.updateBy);
    },
    // 修改时间字典翻译
    updateTimeFormat(row, column) {
      return this.selectDictLabel(this.updateTimeOptions, row.updateTime);
    },
    // 修改时间字典翻译
    extra1Format(row, column) {
      const user = this.filteredStatus.find(user => user.value+'' === row.extra1+'');

      return user ? user.label:'';
    },
    // 修改时间字典翻译
    extra2Format(row, column) {
      return this.selectDictLabel(this.extra2Options, row.extra2);
    },
    // 修改时间字典翻译
    extra3Format(row, column) {
      return this.selectDictLabel(this.extra3Options, row.extra3);
    },
    // 修改时间字典翻译
    extra4Format(row, column) {
      return this.selectDictLabel(this.extra4Options, row.extra4);
    },
    // 采购计划字典翻译
    planIdFormat(row, column) {
      const r = this.filteredPlans.find(r => r.id === row.planId);
      return r ? r.extra1:'';
    },
    // 炼厂字典翻译
    refineryIdFormat(row, column) {
      const r = this.filteredRefinerys.find(r => r.id === row.refineryId);
      return r ? r.refineryName:'';
    },

    reportPersonFormat(row, column) {
      const user = this.filteredUsers.find(user => user.userId === row.reportUserId);

      return user ? user.userName : '';
    },
    // 已发量字典翻译
    sendFormat(row, column) {
      return this.selectDictLabel(this.sendOptions, row.send);
    },
    // 已发车数量字典翻译
    sendCarCountFormat(row, column) {
      return this.selectDictLabel(this.sendCarCountOptions, row.sendCarCount);
    },
    // 已发量字典翻译
    sendWeightFormat(row, column) {
      return this.selectDictLabel(this.sendWeightOptions, row.sendWeight);
    },
    // 出发时间字典翻译
    startTimeFormat(row, column) {
      return this.selectDictLabel(this.startTimeOptions, row.startTime);
    },
    // 预计到达时间字典翻译
    arriveTimeFormat(row, column) {
      return this.selectDictLabel(this.arriveTimeOptions, row.arriveTime);
    },
    // 到库车数量字典翻译
    arriveCarCountFormat(row, column) {
      return this.selectDictLabel(this.arriveCarCountOptions, row.arriveCarCount);
    },
    // 到库重量字典翻译
    arriveWeightFormat(row, column) {
      return this.selectDictLabel(this.arriveWeightOptions, row.arriveWeight);
    },
    // 异常情况字典翻译
    errorFormat(row, column) {
      return this.selectDictLabel(this.errorOptions, row.error);
    },
    // 备注字典翻译
    remarkFormat(row, column) {
      return this.selectDictLabel(this.remarkOptions, row.remark);
    },
    // 上报用户字典翻译
    reportUserIdFormat(row, column) {
      return this.selectDictLabel(this.reportUserIdOptions, row.reportUserId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        extra1: null,
        extra2: null,
        extra3: null,
        extra4: null,
        planId: null,
        refineryId: null,
        send: null,
        sendCarCount: null,
        sendWeight: null,
        startTime: null,
        arriveTime: null,
        arriveCarCount: null,
        arriveWeight: null,
        error: null,
        remark: null,
        reportUserId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
     let planId= this.form.planId
      this.reset();
      this.form.planId=planId
      this.open = true;

      this.title = "添加在途油信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOnway(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改在途油信息";
      });
    },
    handleStatus2(row){
      row.extra1 = 2
      updateOnway(row).then(response => {
        this.msgSuccess("到站成功");
        this.open = false;
        this.getList();
      });
    },
    handleStatus3(row){
      row.extra1 = 3
      updateOnway(row).then(response => {
        this.msgSuccess("收油成功");
        this.open = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.reportUserId = this.userId;

        if (valid) {
          if (this.form.id != null) {
            updateOnway(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOnway(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除在途油信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delOnway(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有在途油信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
        this.download('onway/onway/export', {
          ...this.queryParams
        }, `炼厂分配信息.xlsx`)
          this.exportLoading = false
          // return exportOnway(queryParams);
        }).then(response => {
          // this.download(response.msg);
          // this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
